package gameuserlogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/game/internal/svc"
	"navi-mumbai/app/rpc/game/pb"
	"navi-mumbai/app/rpc/model/pg/game"
	"navi-mumbai/common/key/gamekey"
	"navi-mumbai/common/key/idkey"
	"navi-mumbai/common/key/userkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetOpenIdByUidLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetOpenIdByUidLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOpenIdByUidLogic {
	return &GetOpenIdByUidLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 根据uid查询openid
func (l *GetOpenIdByUidLogic) GetOpenIdByUid(in *pb.GetOpenIdByUidReq) (*pb.GetOpenIdByUidResp, error) {
	defer utils.RecoverPanic()

	var err error
	var resp pb.GetOpenIdByUidResp
	switch in.ProviderId {
	case gamekey.ProviderIdY9Y:
		var uo *game.UserOpenId1
		uo, err = l.svcCtx.UserOpenId1Model.FindOne(l.ctx, in.Uid)
		if err != nil && err != game.ErrNotFound {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
		if uo == nil { // 未生成
			//var incr int64
			//incr, err = l.svcCtx.GameRedis.IncrOpenIdIdx(l.ctx, in.ProviderId)
			//if err != nil {
			//	l.Logger.Errorf("err == ", zap.Error(err))
			//	return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
			//}
			incr, err := l.svcCtx.UserOpenId1Model.FindLMaxUid(l.ctx)
			if err != nil && err != sqlx.ErrNotFound {
				l.Logger.Errorf("err == ", zap.Error(err))
				return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
			}
			if incr < idkey.OpenIdStart {
				incr += idkey.OpenIdStart
			} else {
				incr += 1
			}
			idx := incr % (int64(len(userkey.NickNames)))
			uo = &game.UserOpenId1{
				Uid:      in.Uid,
				OpenId:   incr,
				Nickname: userkey.NickNames[idx],
			}
			_, err = l.svcCtx.UserOpenId1Model.Insert(l.ctx, uo)
			if err != nil {
				l.Logger.Errorf("err == ", zap.Error(err))
				return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
			}
		}
		resp.OpenId = uo.OpenId
		resp.Nickname = uo.Nickname
	default:
		l.Logger.Errorf("provider id error ")
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "provider id error")
	}

	return &resp, nil
}
